//
//  ManagerViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/2/24.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "ManagerViewController.h"
#import <UIImageView+WebCache.h>
#import "SetBlack.h"
#import "BlackManager.h"
@interface ManagerViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, retain)UIImageView *img;//图片名称
@property (nonatomic, copy)NSString *imgPath;//图片路径
@property (nonatomic, retain)UIImageView *headImg;//头像按钮
@property (nonatomic, retain)UITableView *tableview;
@end

@implementation ManagerViewController
-(void)dealloc
{
    [_img release];
    [_imgPath release];
    [_headImg release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{
    //头像
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL sanFang = [[NSUserDefaults standardUserDefaults]boolForKey:@"OtherLogin"];
    //判断是否是三方登录的
    if (sanFang) {
        NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"img"];
        [_headImg sd_setImageWithURL:[NSURL URLWithString:str]];
    }else if (_headImg) {
        NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
        NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
        NSNumber *i = [[NSUserDefaults standardUserDefaults]objectForKey:@"index"];
        NSInteger index = i.intValue;
        NSString *str = [pictureArr objectAtIndex:index];
        if (str.length == 1) {
            [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
        }else if ([userDefaults dataForKey:@"img"]) {
            [_headImg setImage:[UIImage imageWithData:[userDefaults dataForKey:@"img"]]];
        }

    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"账户管理";
    self.tableview = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    [_tableview release];
}
#pragma mark - 设置夜间模式set方法
-(void)setNightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [SetBlack setBackgroundColorWithView:self.view];
    [SetBlack setBackgroundColorWithView:_tableview];
    
}
-(void)setLightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [SetBlack setBackgroundColorWithView:self.view];
    [SetBlack setBackgroundColorWithView:_tableview];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil]autorelease];
    [SetBlack setCellColorWithCell:cell];
    [SetBlack setLableTitleColorWithArr:@[cell.textLabel]];
    if (indexPath.row == 0) {
        cell.textLabel.text = @"头像";
        //头像
        self.headImg = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width - cell.frame.size.height - 20, 10, cell.frame.size.height, cell.frame.size.height)];
       _headImg.layer.cornerRadius = (cell.frame.size.height) / 2;
        _headImg.clipsToBounds = YES;
        _headImg.userInteractionEnabled = YES;
        [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeAction)];
        [_headImg addGestureRecognizer:tap];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //判断是否是三方登录
        BOOL sanFang = [[NSUserDefaults standardUserDefaults]boolForKey:@"OtherLogin"];
        //判断是否是三方登录的
        if (sanFang) {
            NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"img"];
            [_headImg sd_setImageWithURL:[NSURL URLWithString:str]];
        }else if (_headImg) {
            //通过在数组中的位置获取图片
            NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
            NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
            NSNumber *i = [[NSUserDefaults standardUserDefaults]objectForKey:@"index"];
            NSInteger index = i.intValue;
            NSString *str = [pictureArr objectAtIndex:index];
            if (str.length == 1) {
                [_headImg setImage:[UIImage imageNamed:@"qiaoba.png"]];
            }else if ([userDefaults dataForKey:@"img"]) {
                [_headImg setImage:[UIImage imageWithData:[userDefaults dataForKey:@"img"]]];
            }
        }

        [cell addSubview:_headImg];
    }
    if (indexPath.row == 1) {
        cell.textLabel.text = @"昵称";
        UIButton *nameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        nameBtn.frame = CGRectMake(self.view.frame.size.width / 2, 10, cell.frame.size.width / 2 - 20, cell.frame.size.height);
        nameBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
        [nameBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [nameBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [nameBtn setTitle:name forState:UIControlStateNormal];
        [cell addSubview:nameBtn];
    }
    if (indexPath.row == 2) {
        UIButton *tuichu = [UIButton buttonWithType:UIButtonTypeSystem];
        tuichu.frame = CGRectMake(0, 0, cell.frame.size.width / 4, cell.frame.size.height / 2);
        tuichu.center = CGPointMake(self.view.frame.size.width / 2, cell.frame.size.height / 2);
        [tuichu setTitle:@"退出登录" forState:UIControlStateNormal];
        [tuichu setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        tuichu.titleLabel.font = [UIFont systemFontOfSize:18];
        [tuichu addTarget:self action:@selector(tuichuAction) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:tuichu];
    }
    return cell;
}
#pragma mark - 改变头像方法
-(void)changeAction
{
    BOOL otherLogin = [[NSUserDefaults standardUserDefaults]boolForKey:@"OtherLogin"];
    if (!otherLogin) {
        //弹窗
        UIAlertController *promptAlert = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        //照相机
        
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //
            NSLog(@"照相机");
            [self cameraAction];
            
        }];
        [promptAlert addAction:cameraAction];
        //相册
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //
            [self pickerAction];
            NSLog(@"相册");
        }];
        [promptAlert addAction:photoAction];
        
        //取消
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //
            NSLog(@"取消");
        }];
        [promptAlert addAction:cancleAction];
        [self presentViewController:promptAlert animated:YES completion:^{
            
        }];

    }else{
        //三方登录时不能修改头像
    }
    
    
    
}
#pragma mark - 照相机
-(void)cameraAction
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
            //
        }];
        [picker release];
    }else{
        //如果没有提示用户
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"你没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alter animated:YES completion:^{
            //
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];
    }
}
#pragma mark - 相册picker
-(void)pickerAction
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc]init];
    //静态方法判断设备是否支持图库功能
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImage.delegate = self;
    //是否可编辑 剪裁
    pickerImage.allowsEditing = YES;
    //跳转到相册页面
    [self presentViewController:pickerImage animated:YES completion:^{
        //
    }];
    [pickerImage release];
}
#pragma mark - 相册的协议方法
//相册的协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //将编辑后的图片保存在image中
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //当图片不为空是显示并保存图片
    if (image != nil) {
        self.img.image = image;
        //以下是保存文件到沙盒路径下
        //把图片转换为NSData类型的数据来保存文件
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像
            data = UIImagePNGRepresentation(image);
        }else{
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        //保存
        NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
        NSNumber *i = [[NSUserDefaults standardUserDefaults]objectForKey:@"index"];
        NSInteger index = i.intValue;
        NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
        [pictureArr replaceObjectAtIndex:index withObject:data];
        [NSKeyedArchiver archiveRootObject:pictureArr toFile:picturePath];
        //变换后的图片设置为单例显示
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:data forKey:@"img"];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 9;
}
-(void)tuichuAction
{
   
    //弹窗
    UIAlertController *promptAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定退出" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        NSLog(@"确定");
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"register"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    [promptAlert addAction:rightAction];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //
        NSLog(@"取消");
    }];
    [promptAlert addAction:cancleAction];
    [self presentViewController:promptAlert animated:YES completion:^{
        
    }];
    NSLog(@"退出成功");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
